package com.javachmapi.ftp.controller;

import com.javachmapi.ftp.constants.Constants;
import com.javachmapi.ftp.util.FtpUtil;
import com.javachmapi.ftp.util.FtpUtils;
import com.javachmapi.ftp.vo.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * ftp文件上传类
 * create by 宋利军
 */
@RestController
@RequestMapping("/ftp")
@Api(value = "FTPFileUploadController", tags = "Ftp相关接口", description = "上传、下载、删除")
public class FTPFileUploadController {

    @PostMapping("/uploadFile")
    @ApiOperation(value = "上传文件", notes = "FTP实现上传文件至服务器")
    public ResponseData uploadFile(@RequestParam(name = "file") @ApiParam(value = "选择文件", required = true) MultipartFile file){
        try{
            if (!file.isEmpty()){
                //获取图片或文件的后缀名
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                //拼接图片或文件名称，32位随机uuid+后缀名
                String fileName = UUID.randomUUID().toString().replace("-", "").toLowerCase() + suffix;
                InputStream inputStream = file.getInputStream();
                //调用ftp上传文件工具类，返回true成功，返回false失败
                Boolean flag = FtpUtils.uploadFile(Constants.BASEPATH,fileName,inputStream);
                if(flag == true){
                    //这里按功能需求做相应处理即可
                    return ResponseData.success("上传成功！");
                }
            }
        }catch (Exception e) {
            return ResponseData.failure("上传出现异常！");
        }
        return ResponseData.failure("上传失败！");
    }

    @PostMapping("/downloadFile")
    @ApiOperation(value = "下载文件", notes = "FTP实现从服务器上下载文件")
    public ResponseData downloadFile(@RequestParam(name = "fileName") @ApiParam(value = "下载文件的名称", required = true) String fileName,
                                     @RequestParam(name = "localpath") @ApiParam(value = "下载后的文件路径 ", defaultValue = "C:\\Users\\Administrator\\Desktop" ,required = false) String localpath){
        boolean bl = FtpUtils.downloadFile(Constants.FTP_BASEPATH,fileName,localpath);
        if(bl){
            return ResponseData.success("下载文件成功！");
        }
        return ResponseData.failure("下载文件失败！");
    }

    @PostMapping("/deleteFile")
    @ApiOperation(value = "删除文件", notes = "FTP实现从服务器上删除文件")
    public ResponseData deleteFile(@RequestParam(name = "fileName") @ApiParam(value = "删除的文件名", required = true) String fileName){
        boolean bl = FtpUtils.deleteFile(Constants.BASEPATH,fileName);
        if(bl){
            return ResponseData.success("删除文件成功！");
        }
        return ResponseData.failure("删除文件失败！");
    }
}

